package org.longs.stream;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class LittleAccessFile extends RandomAccessFile {
    private final byte[] shortByte = new byte[2];
    private final byte[] intByte = new byte[4];
    private final byte[] LongByte = new byte[8];
    public LittleAccessFile(String name, String mode) throws FileNotFoundException {
        super(name, mode);
    }

    public LittleAccessFile(File file, String mode) throws FileNotFoundException {
        super(file, mode);
    }


    public short readLittleShort() throws IOException {
        for (int i = 0; i < shortByte.length; i++) {
            getRead(shortByte, i);
        }
        return ByteBuffer
                .wrap(shortByte)
                .order(ByteOrder.LITTLE_ENDIAN)
                .getShort();
    }

    private void getRead(byte[] shortByte, int index) throws IOException {
        shortByte[index] = this.readByte();
    }


    public int readLittleInt() throws IOException {
        for (int i = 0; i < intByte.length; i++) {
            getRead(intByte, i);
        }
        return ByteBuffer
                .wrap(intByte)
                .order(ByteOrder.LITTLE_ENDIAN)
                .getInt();
    }


    public long readLittleLong() throws IOException{
        for (int i = 0; i < LongByte.length; i++) {
            getRead(LongByte, i);
        }
        return ByteBuffer
                .wrap(LongByte)
                .order(ByteOrder.LITTLE_ENDIAN)
                .getLong();
    }
}
